﻿using MaterialDesignThemes.Wpf;
using NoteBook_Product.DialogsService;
using NoteBook_Product.Extensions;
using NoteBook_Product.Services;
using NoteBook_Shared.Dtos;
using NoteBook_Shared.Parameters;
using Prism.Commands;
using Prism.Ioc;
using Prism.Regions;
using System.Collections.ObjectModel;
using System.Diagnostics;

namespace NoteBook_Product.ViewModels
{
    public class ToDoViewModel : NavigationViewModel
    {
        private readonly IToDoService _toDoService;
        private readonly IDialogHostService _dialogHost;

        public ToDoViewModel(IToDoService toDoService, IContainerProvider containerProvider) : base(containerProvider)
        {
            this._toDoService = toDoService;
            _dialogHost = containerProvider.Resolve<IDialogHostService>();
            ToDoDtos = new();

            ExecuteCommand = new(Execute);

            SelectdCommand = new(Selected);

            DeleteCommand = new(Delete);
        }

        #region 字段

        /// <summary>
        /// 待办事项列表
        /// </summary>
        public ObservableCollection<ToDoDto> ToDoDtos { get; set; }

        /// <summary>
        /// 是否打开右侧弹出框
        /// </summary>
        private bool isRightDrawerOpen;

        public bool IsRightDrawerOpen
        {
            get { return isRightDrawerOpen; }
            set { isRightDrawerOpen = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 当前对象
        /// </summary>
        private ToDoDto currentDto;

        public ToDoDto CurrentDto
        {
            get { return currentDto; }
            set { currentDto = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 查询条件
        /// </summary>
        private string search;

        public string Search
        {
            get { return search; }
            set { search = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 下拉框
        /// </summary>
        private int selectdIndex;

        public int SelectdIndex
        {
            get { return selectdIndex; }
            set { selectdIndex = value; }
        }


        #endregion

        #region 命令

        /// <summary>
        /// 打开弹出框
        /// </summary>
        public DelegateCommand<string> ExecuteCommand { get; set; }

        /// <summary>
        /// 查看单条数据
        /// </summary>
        public DelegateCommand<ToDoDto> SelectdCommand { get; set; }

        /// <summary>
        /// 删除
        /// </summary>
        public DelegateCommand<ToDoDto> DeleteCommand { get; set; }

        #endregion

        /// <summary>
        /// 导航跳转
        /// </summary>
        /// <param name="navigationContext"></param>
        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);
            GetDataAsync();
        }

        private void Execute(string obj)
        {
            switch (obj)
            {
                case "新增": Add(); return;
                case "查询": GetDataAsync(); return;
                case "保存": Save(); return;
            }
        }

        /// <summary>
        /// 获取全部数据
        /// </summary>
        private async void GetDataAsync() => await CommonMenthodInvoke(async () =>
        {
            var list = await _toDoService.GetAllFilterAsync(new ToDoParameter()
            {
                PageIndex = 0,
                PageSize = 100,
                Search = search,
                Status = SelectdIndex == 0 ? null : SelectdIndex >> 1
            });

            if (list.Status)
            {
                ToDoDtos.Clear();
                foreach (var item in list.Result.Items)
                {
                    ToDoDtos.Add(item);
                }
            }
        });

        /// <summary>
        /// 获取编辑数据
        /// </summary>
        /// <param name="dto"></param>
        private async void Selected(ToDoDto dto) => await CommonMenthodInvoke(async () =>
        {
            var todoResult = await _toDoService.GetFirstOfDefaultAsync(dto.Id);

            if (todoResult.Status)
            {
                CurrentDto = todoResult.Result;
                IsRightDrawerOpen = true;
            }
        });

        private void Add()
        {
            CurrentDto = new();
            IsRightDrawerOpen = true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        private async void Save()
        {
            if (string.IsNullOrEmpty(CurrentDto.Title) || string.IsNullOrEmpty(CurrentDto.Content)) return;

            bool isTrue = false;

            await CommonMenthodInvoke(async () =>
            {
                if (CurrentDto.Id > 0)
                {
                    var updateResult = await _toDoService.UpdateAsync(currentDto);
                    isTrue = updateResult.Status;
                }
                else
                {
                    var addResult = await _toDoService.AddAsync(CurrentDto);
                    isTrue = addResult.Status;
                }

                IsRightDrawerOpen = false;
            });

            if (isTrue) GetDataAsync();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="dto"></param>
        /// <exception cref="NotImplementedException"></exception>
        private async void Delete(ToDoDto dto)
        {
            var dialogResult = await _dialogHost.Question("温馨提示", $"确认删除待办事项：{dto.Title}？");
            if (dialogResult.Result != Prism.Services.Dialogs.ButtonResult.OK) return;

            bool isTrue = false;
            await CommonMenthodInvoke(async () =>
            {
                var deleteResult = await _toDoService.DeleteAsync(dto.Id);
                isTrue = deleteResult.Status;
            });

            if (isTrue)
            {
                GetDataAsync();
            }
        }

        /// <summary>
        /// 通用方法调用
        /// </summary>
        /// <param name="action">委托方法</param>
        /// <returns></returns>
        private async Task CommonMenthodInvoke(Func<Task> func)
        {
            try
            {
                UpdateLoading(true);

                // 执行方法
                await func?.Invoke();   // 必须是Task等待，否则loading框不出现

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                UpdateLoading(false);
            }
        }
    }
}